package com.haonan.springboot_exercise.service.impl;

import com.alibaba.fastjson.JSON;
import com.haonan.springboot_exercise.bean.Email;
import com.haonan.springboot_exercise.bean.pojo.MsgResult;
import com.haonan.springboot_exercise.bean.pojo.MyMailMessage;
import com.haonan.springboot_exercise.bean.pojo.Result;
import com.haonan.springboot_exercise.bean.pojo.ServicePort;
import com.haonan.springboot_exercise.dao.SmtpServerDao;
import com.haonan.springboot_exercise.dao.UserDao;
import com.haonan.springboot_exercise.netty.client.SmtpClient;
import com.haonan.springboot_exercise.netty.server.SmtpServer;
import com.haonan.springboot_exercise.service.SmtpServerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author haonan
 * @date 2021/4/15 21:37
 **/
@Component
public class SmtpServerImpl implements SmtpServerService {
    private final String LOCAL_IP = "127.0.0.1";
    @Autowired
    SmtpServerDao smtpServerDao;
    @Autowired
    UserDao userDao;

    @Override
    public String getHELOResult(String payload) {
        return smtpServerDao.getSmtpDomain(LOCAL_IP).equals((payload))
                ? JSON.toJSONString(new MsgResult(250,"HELOReady"))
                : JSON.toJSONString(new MsgResult(350,"HELOWrong"));
    }

    @Override
    public String getMAILResult(String payload) {
         return userDao.userCanSmtp(payload)
                 ? JSON.toJSONString(new MsgResult(251,"MAILReady"))
                 : JSON.toJSONString(new MsgResult(351,"MAILWrong"));
    }

    @Override
    public String getRCPTResult(String payload) {
        // 把payload里面的收件人邮箱用String[]存储
        String[] to = payload.split(",");
        // 把字符串数组第一个字符串的"["和最后一个字符串的"]"去掉
        to[0] = to[0].substring(1);
        // 调试过程发现to[1]到to[length-1]字符串前面都有一个空格，加了以下这句就好了
        for (int i = 0; i < to.length; i++) {
            to[i] = to[i].trim();
        }
        to[to.length-1] = to[to.length-1].substring(0,to[to.length-1].length()-1);

        List<String> list = new ArrayList<>();
        boolean flag = true;
        for (String s : to) {
            if(!userDao.userCanPop(s)){
                flag = false;
                list.add(s);
            }
        }

        return flag
                ? JSON.toJSONString(new MsgResult(252,"RCPTReady"))
                : JSON.toJSONString(new MsgResult(352,list.toString()));
    }

    @Override
    public String getSUBJResult(String payload) {
//        return payload.getBytes().length < 100
//                ? JSON.toJSONString(new MsgResult(253,"SUBJReady"))
//                : JSON.toJSONString(new MsgResult(353,"SUBJWrong"));
        return JSON.toJSONString(new MsgResult(253,"SUBJReady"));
    }

    @Override
    public String getTIMEResult(String payload) {
        return JSON.toJSONString(new MsgResult(254,"TIMEReady"));
    }

    @Override
    public String getTEXTResult(String payload) {
//        return TEXTIsLegal(payload)
//                ? JSON.toJSONString(new MsgResult(300,"OK"))
//                : JSON.toJSONString(new MsgResult(400,"Failed"));
        return JSON.toJSONString(new MsgResult(300,"OK"));
    }

    @Override
    public Boolean storeMails(MyMailMessage myMailMessage) {
        String from = myMailMessage.getFrom();
        String sent_time = myMailMessage.getSent_time();
        String subject = myMailMessage.getSubject();
        String text = myMailMessage.getText();
        for (String to : myMailMessage.getTo()) {
            smtpServerDao.storeMail(new Email(from, to, sent_time, subject, text));
        }
        return true;
    }

    @Override
    public Result closeSmtpServer() throws Exception {
        SmtpClient smtpClient = new SmtpClient();
        smtpClient.run();
        smtpClient.getSmtpClientHandler().sendDataToServer(smtpClient.getChannel(), "CLOSE_SMTP");
        smtpServerDao.setState(false);
        return Result.succ(null);
    }

    /**
     * 打开Smtp服务
     *
     * @return
     * @throws Exception
     */
    @Override
    public Result openSmtpServer() throws Exception {
        new Thread(()->{
            SmtpServer smtpServer = new SmtpServer();
            smtpServer.start(new InetSocketAddress("127.0.0.1",smtpServerDao.getSmtpPort("127.0.0.1")));
        }).start();
        smtpServerDao.setState(true);
        return Result.succ(null);
    }
}
